package com.codedog.utils;

import javax.sound.sampled.*;
import java.io.File;
import java.io.SequenceInputStream;

public class CodeDogAudioUtil {
    public static void mergeAudio(String inputFile1, String inputFile2, String outputFile) throws Exception {
        // 打开第一个 WAV 文件
        File file1 = new File(inputFile1);
        AudioInputStream audioStream1 = AudioSystem.getAudioInputStream(file1);

        // 打开第二个 WAV 文件
        File file2 = new File(inputFile2);
        AudioInputStream audioStream2 = AudioSystem.getAudioInputStream(file2);

        // 获取音频格式
        AudioFormat format1 = audioStream1.getFormat();
        AudioFormat format2 = audioStream2.getFormat();

        // 确保两个文件的格式一致
        if (!format1.matches(format2)) {
            throw new UnsupportedAudioFileException("音频文件格式不一致！");
        }

        // 获取合并后的音频数据流
        AudioInputStream appendedFiles = new AudioInputStream(
                new SequenceInputStream(audioStream1, audioStream2),
                format1,
                audioStream1.getFrameLength() + audioStream2.getFrameLength()
        );

        // 创建输出 WAV 文件
        File output = new File(outputFile);
        AudioSystem.write(appendedFiles, AudioFileFormat.Type.WAVE, output);

        // 关闭所有流
        audioStream1.close();
        audioStream2.close();
        appendedFiles.close();

        System.out.println("音频拼接完成，输出文件：" + outputFile);
    }

    public static void main(String[] args) {
        try {
            mergeAudio("C:\\Users\\66525\\Desktop\\1734333534291.wav", "C:\\Users\\66525\\Desktop\\1734336331797.wav", "C:\\Users\\66525\\Desktop\\Demo.wav");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
